import koa from 'koa';
import render from 'koa-ejs';
import webpack from 'webpack';
import config from '../webpack.config.babel';
import path from 'path'


const app = new koa();
const Loadable = require('react-loadable');

const compiler = webpack(config);


render(app, {
    root: path.join(__dirname, '../dist/view'),
    layout: false,
    viewExt: 'html',
    cache: false,
});


(async function f() {
    if (process.env.NODE_ENV !== 'production') {
// webpack compile
        const options = {
            publicPath: '/static/',
            // noInfo: true,
            stats: {colors: true},
            // serverSideRender: true
        };
        app.use(async (ctx, next) => {
            await require('webpack-dev-middleware')(compiler, options)(ctx.req, {
                end: (content) => {
                    ctx.body = content
                },
                setHeader: (name, value) => {
                    ctx.set(name, value)
                }
            }, next)
        });

        app.use(async function (ctx, next) {
            await require('webpack-hot-middleware')(compiler)(ctx.req, ctx.res, next)
        });


    } else {
        await compiler.run((err, stats) => {
            stats = stats.toJson({
                assets: false,
                hash: true
            });
            // console.log('~~~~~~~~~~~~~~`', stats)
        })
    }
})()
app.use(require('koa-static')(path.resolve(__dirname, '../dist'), {
    maxAge: 365 * 24 * 60 * 60,
    gzip: true
}));
// mock
app.use(require('./mockMiddleware'));
app.use(require('./ssrMiddleware'));
// app.disable('x-powered-by');

Loadable.preloadAll().then(() => {
    app.listen(3080, () => {
        console.info(`Listened at http://localhost:3080`);
    });
})